package work.linruchang.util.bean;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.sql.SqlExecutor;
import lombok.SneakyThrows;
import work.linruchang.util.bean.wrapper.QueryWrapper;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SQL执行器
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/04/24
 * @since 1.8
 **/
public class EnhanceDbSqlExecutorUtil extends SqlExecutor {

    /**
     * 查询
     * @param queryWrapper SQL条件
     * @return
     */
    @SneakyThrows
    public static List<Map<String,Object>> query(QueryWrapper queryWrapper) {

        if (queryWrapper == null) {
            return CollUtil.newArrayList();
        }

        DataSource ds = DSFactory.get();
        Connection connection = ds.getConnection();
        ResultSet resultSet = null;
        resultSet = callQuery(connection, queryWrapper.getSQL(), queryWrapper.getSqlParams().toArray());


        List<Map<String,Object>> result = new ArrayList();

        ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnCount = rsmd.getColumnCount();

        while (resultSet.next()) {
            Map row = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                row.put(rsmd.getColumnName(i), resultSet.getObject(i));
            }
            result.add(row);
        }
        return result;
    }



    /**
     * 查询
     * @param queryWrapper SQL
     * @param targetClazz 将每行结果结果集转换的对象
     */
    @SneakyThrows
    public static <T,M> List<M> queryToBean(QueryWrapper<T> queryWrapper, Class<M> targetClazz) throws SQLException {
        Assert.notNull(targetClazz,"缺乏转换的目标反射，请检查");
        List<Map<String,Object>> results = query(queryWrapper);
        List<M> collect = results.stream()
                .map(row -> BeanUtil.toBean(row, targetClazz))
                .collect(Collectors.toList());
        return collect;

    }

    /**
     * 查询
     * @param queryWrapper SQL
     */
    public static <T> List<T> queryToBean(QueryWrapper<T> queryWrapper) throws SQLException {
        return queryToBean(queryWrapper,queryWrapper.getFirstTableClazz());
    }


}
